package com.goldplusgold.tradedelay.app.trade.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.market.eventbus.TotalPositionProfitAndLossMessageEvent;
import com.goldplusgold.tradedelay.app.trade.activity.TradeWebViewActivity;
import com.goldplusgold.tradedelay.app.trade.networkservice.ApiConfig;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.MyAssets;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.widget.TitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2017/5/20.
 */

public class MyAssetsFragment extends BaseFragment implements Handler.Callback {

    @BindView(R.id.id_my_assets_title)
    TitleView mMyAssetsTitle;
    @BindView(R.id.id_text_view_floating_pl)
    TextView mTextViewFloatingPl;
    @BindView(R.id.id_text_view_position_deposit)
    TextView mTextViewPositionDeposit;
    @BindView(R.id.id_text_view_available_amount)
    TextView mTextViewAvailableAmount;
    @BindView(R.id.id_text_view_extractable_amount)
    TextView mTextViewExtractableAmount;
    @BindView(R.id.id_text_view_dynamic_rights)
    TextView mDynamicRights;
    private Handler handler = new Handler(this);

    public static MyAssetsFragment newInstance() {

        Bundle args = new Bundle();

        MyAssetsFragment fragment = new MyAssetsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_my_assets;
    }


    @Override
    protected void initView() {
        super.initView();
        mMyAssetsTitle.getTitletextView().setVisibility(View.VISIBLE);
        mMyAssetsTitle.getTitletextView().setText("我的资产");
        mMyAssetsTitle.getBackView().setVisibility(View.VISIBLE);
        mMyAssetsTitle.getBackView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
        new LoadMyAssetsAsyncTask().execute(AsyncTask.TYPE_NET);
    }


    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_REFRESH_CODE:
                new LoadMyAssetsAsyncTask().execute(AsyncTask.TYPE_NET);
                break;
            case NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE:
                String message = (String) msg.obj;
                ActivityUtils.forceQuit(getActivity(), message);
                break;
        }

        return true;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void totalPositionProfitAndLossMessageEvent(TotalPositionProfitAndLossMessageEvent event) {
        double totalPositionProfitAndLoss = event.getTotalPositionProfitAndLoss();
        if (totalPositionProfitAndLoss > 0) {
            mTextViewFloatingPl.setText("+" + String.valueOf(totalPositionProfitAndLoss));
            mTextViewFloatingPl.setTextColor(getResources().getColor(R.color.color_red));
        } else if (totalPositionProfitAndLoss == 0) {
            mTextViewFloatingPl.setText(String.valueOf(totalPositionProfitAndLoss));
            mTextViewFloatingPl.setTextColor(getResources().getColor(R.color.color_gray));
        } else {
            mTextViewFloatingPl.setText(String.valueOf(totalPositionProfitAndLoss));
            mTextViewFloatingPl.setTextColor(getResources().getColor(R.color.color_green));
        }

    }


    @OnClick(R.id.btn_roll_in_and_out)
    public void onViewClicked() {
        actionBrowserPage(ApiConfig._CASH_OPERATION_URL);
    }


    public class LoadMyAssetsAsyncTask extends AsyncTask<Void, Void, MyAssets> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected MyAssets doInBackground(Void... params) {

            try {
                MyAssets MyAssets = TradeService.getInstance().getMyAssets();
                return MyAssets;
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(MyAssets myAssets) {
            super.onPostExecute(myAssets);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (myAssets == null) {
                return;
            }
            mTextViewPositionDeposit.setText(myAssets.getPositionMargin());
            mTextViewAvailableAmount.setText(myAssets.getAvailableCash());
            mTextViewExtractableAmount.setText(myAssets.getWithdrawableCash());
            mDynamicRights.setText(myAssets.getDynamicRights());
            sendRefreshMessage();
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    private void sendRefreshMessage() {
        final Message message = handler.obtainMessage();
        message.what = NetWorkConstant.NETWORK_SERVER_REFRESH_CODE;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                handler.sendMessage(message);
            }
        }, 5 * 1000);
    }

    private void actionBrowserPage(String url) {
        Intent intent = new Intent(getActivity(), TradeWebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
